import {iMicroApp, iMicroTabMeta} from "@peryl/micro-web";
import {createCache, getComponentCls} from "@peryl/react-compose";
import {MicroAppModule} from "./MicroAppModule";
import {createEffects} from "@peryl/utils/createEffects";

export const MicroAppCache = MicroAppModule.createRegistration((option) => {

  const { effects } = createEffects();

  const staticState = {
    currentRoute: null as null | string,
  };

  const cache = createCache<Record<string, iMicroTabMeta[]>>(() => ({
    cacheName: getComponentCls('@@PAGE_THEME_IS_DARK'),
    envName: option.config.envName,
  }));

  const apply: iMicroApp["cache"]["apply"] = async ({ route, handleApplied, handleNoCache }) => {

    staticState.currentRoute = route;

    let tabs = (cache.get() || {})[staticState.currentRoute];
    if (!tabs || !tabs.length) {
      await handleNoCache();
      await handleApplied();
    } else {
      tabs = await option.config.formatTabs(tabs);
      option.state.tabs = tabs;
      await handleApplied();
    }

    effects.clear();
    effects.push(
      option.hooks.onPagesChange.use(() => {
        save();
      })
    );
  };

  const clear = (route?: string) => {
    const routeMap = cache.get() || {};
    const r = route || staticState.currentRoute;
    if (!!r) {
      delete routeMap[r];
      cache.save(routeMap);
    }
  };

  const save = (route?: string) => {
    const _route = route || staticState.currentRoute;
    if (!_route) {
      return;
    }
    const tabs = option.state.tabs.map((tab: iMicroTabMeta) => {
      const isShow = !!tab.pages.find(i => i.show);
      return {
        ...tab,
        pages: !isShow ? [] : [{
          ...tab.pages[0],
          show: true,
        }]
      };
    });
    const routeMap = cache.get() || {};
    routeMap[_route] = tabs;
    cache.save(routeMap);
  };

  return { apply, clear, save };
});
